document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);

var jsonKey = "json:";

function CSVtoArray(text) {
  var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
  var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;
  // Return NULL if input string is not well formed CSV string.
  if (!re_valid.test(text)) return null;
  var a = [];                     // Initialize array to receive values.
  text.replace(re_value, // "Walk" the string using replace with callback.
    function(m0, m1, m2, m3) {
      // Remove backslash from \' in single quoted values.
      if      (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));
      // Remove backslash from \" in double quoted values.
      else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
      else if (m3 !== undefined) a.push(m3);
      return ''; // Return empty string.
    });
  // Handle special case of empty last value.
  if (/,\s*$/.test(text)) a.push('');
  return a;
};

function getPayload( object ) {
  var payload = {
    data: JSON.stringify( object )
  };
  return payload;
}

function readSingleFile(e) {
  var file = e.target.files[0];
  if (!file) {
    return;
  }
  var reader = new FileReader();
  reader.onload = function(event) {
    var line;
    var jsonLocation;
    var messageEvent;
    var textFile = event.target;
    var asText = textFile.result;
    var lines = asText.split( '\n');
    if ( !lines || lines.length == 0 ) return;
    var seriesNames = [];
    onMessage (
      getPayload(
        {
          type: "command",
          command: "config",
          graphType: "line",
          parameters: []
        }));


    onMessage(
      getPayload(
        {
          type: "command",
          command: "historicalStart"
        }));


    for ( var index = 0; index < lines.length; index++ ) {
      line = lines[index].trim();
      if ( line.length == 0 ) continue;
      var csvValues = CSVtoArray( line );
      if ( index == 0 ) {
        csvValues.forEach( function( header ) {
          seriesNames.push( header.trim() );
        });
        seriesNames.shift(); //first one is a category/x axis name
        continue;
      }


      var xValue = parseFloat( csvValues[0] );
      for ( var seriesNumber = 0; seriesNumber + 1 < csvValues.length; seriesNumber++ ) {
        var json = {
          "seriesName": seriesNames[ seriesNumber ],
          "seriesNumber": seriesNumber,
          "data" : [
            {
              "x": xValue,
              "y": parseFloat( csvValues[seriesNumber + 1] )
            }
          ]
        }
        onMessage( getPayload( json ) );
      }



      if ( ( index + 1 ) % 100 == 0 ) {
        console.debug( "Processed ", index + 1, " Total: ", lines.length );
      }
    }
    console.info("Completed file load")

    onMessage (
      getPayload({
        type: "command",
        command: "historicalEnd"
      }));

  };
  reader.readAsText(file);
  debugToggle();
}